using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml;
using System.Xml.Linq;

namespace RStein.Posterous.API
{
    public abstract class DictionaryResponseParserBase : IResultResponseParser<Dictionary<String, String>>
    {
        #region constructors

        public DictionaryResponseParserBase()
        {
        }

        #endregion constructors

        #region methods
        protected virtual void OnParserStart(Stream stream, XElement root)
        {

        }

        protected virtual void OnParserEnd(Stream stream, XElement root)
        {

        }

        protected  virtual void OnResult(Dictionary<string, string> values)
        {
            
        }

        protected virtual XElement ChangeParserRoot(XElement root)
        {
            return root;
        }

        
        #endregion methods
        #region Implementation of IResultResponseParser<out Dictionary<string,string>>

        public Dictionary<string, string> GetResults(Stream stream)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }


            XmlReader reader = XmlReader.Create(stream);
            XElement root = XElement.Load(reader);
            root = ChangeParserRoot(root);

            OnParserStart(stream, root);
            
            
            var result = (from elem in root.Elements()
                          select new
                          {
                              Key = elem.Name.ToString(),
                              Value = (string) elem
                          })
                .ToDictionary(elm => elm.Key, elm => elm.Value);

            OnResult(result);
            OnParserEnd(stream, root);
            return result;
            
            

        }

        
        #endregion
    }
}